package com.cloudeye.logtest.netty;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Created by lafangyuan on 2021/1/26.
 */
public class BIOServer {

    public void singleThreadServer() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        PrintWriter out = null;
        Socket socket = null;
        while (true){
            socket = serverSocket.accept();
            System.out.println("获取到连接："+socket.toString());
            InputStream inputStream = socket.getInputStream();
            System.out.println("接收到数据了");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String body = bufferedReader.readLine();
            if(body!=null){
                System.out.println("接收的数据："+body);
            }
        }
    }
    public void multiThreadServer() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        PrintWriter out = null;
        while (true){
            Socket socket = serverSocket.accept();
            new Thread(()->{
                System.out.println("获取到连接："+socket.toString());
                InputStream inputStream = null;
                try {
                    inputStream = socket.getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String body = null;
                while (true){
                    try {
                        body = bufferedReader.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if(body!=null){
                        System.out.println("接收的数据："+body);
                    }
                }
            }).start();

        }
    }


    public void reactBioServer0() throws IOException {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.bind(new InetSocketAddress(8888));
        socketChannel.configureBlocking(false);
        while (true){
            //非阻塞
            final SocketChannel client = socketChannel.accept();
            if(client!=null){
                System.out.println("获取到连接："+client.toString());
                ByteBuffer buffer = ByteBuffer.allocate(128);
                //阻塞
                client.read(buffer);
                //读取到数据后又丢掉连接重新开始执行accept了。
                System.out.println("接收的数据："+new String(buffer.array()));
            }else {
                System.out.println("没有获取到连接");
            }
        }
    }
    public void reactBioServer1() throws IOException {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.bind(new InetSocketAddress(8888));
        socketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true){
            //操作系统层面执行
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                //移除
                iterator.remove();
                if(selectionKey.isAcceptable()){
                    handelAcceptable(selector,selectionKey);
                }
                if(selectionKey.isReadable()){
                    handelReadable(selectionKey);
                }
            }
        }
    }

    private void handelReadable(SelectionKey selectionKey) throws IOException {
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        ByteBuffer buffer = ByteBuffer.allocate(128);
        channel.read(buffer);
        System.out.println("接收的数据："+new String(buffer.array()));
    }

    private void handelAcceptable(Selector selector,SelectionKey selectionKey) throws IOException {
        ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
        final SocketChannel client = channel.accept();
        System.out.println("获取到连接："+client.toString());
        client.configureBlocking(false);
        client.register(selector,SelectionKey.OP_READ);
    }

    public void aioServer() throws IOException, ExecutionException, InterruptedException {
        AsynchronousServerSocketChannel socketChannel = AsynchronousServerSocketChannel.open();
        socketChannel.bind(new InetSocketAddress(8888));
        socketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel client, Object attachment) {
                System.out.println("获取到连接："+client.toString());
                socketChannel.accept(null,this);
                while (true){
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    Future<Integer> future = client.read(buffer);
                    try {
                        if(future.get()>0){
                            buffer.flip();
                            System.out.println("接收的数据："+new String(buffer.array()));
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failed(Throwable exc, Object attachment) {

            }
        });
        //阻塞主线程
        System.in.read();
    }
    public static void main(String[] args) throws IOException {

    }
}
